package com.gs.SynAntiWandering.fragment;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.gs.SynAntiWandering.R;
import com.gs.SynAntiWandering.activity.CameraAngleActivity;
import com.gs.SynAntiWandering.activity.LoginActivity;
import com.gs.SynAntiWandering.apiresult.ApiResultData;
import com.gs.SynAntiWandering.constant.AllConstants;
import com.gs.SynAntiWandering.constant.EventCode;
import com.gs.SynAntiWandering.db.bean.Event;
import com.gs.SynAntiWandering.db.dto.ShortDto;
import com.gs.SynAntiWandering.db.dto.VersionDto;
import com.gs.SynAntiWandering.dialog.CommDialogUtils;
import com.gs.SynAntiWandering.dialog.InfoNavTypeDialog;
import com.gs.SynAntiWandering.dialog.LoadingDialogUtils;
import com.gs.SynAntiWandering.dialog.ShortDialog;
import com.gs.SynAntiWandering.fragment.base.BaseFragment;
import com.gs.SynAntiWandering.presenter.SettingsPresenter;
import com.gs.SynAntiWandering.service.CloseService;
import com.gs.SynAntiWandering.util.ActivityUtil;
import com.gs.SynAntiWandering.util.AppUtil;
import com.gs.SynAntiWandering.util.LanguageUtils;
import com.gs.SynAntiWandering.util.NotificationUtil;
import com.gs.SynAntiWandering.util.SPUtil;
import com.gs.SynAntiWandering.util.ToastUtil;
import com.gs.SynAntiWandering.view.ISettingsView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class SettingsFragment extends BaseFragment<ISettingsView, SettingsPresenter> implements ISettingsView {

    private TextView tvLanguage, tvSite, tvVersion, tvType, tvAngle, tvPhoto, tvUser;
    private List<ShortDto> listLang, listPhoto;
    private ShortDialog dialogLang, dialogPhoto;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_settings;
    }

    @Override
    protected SettingsPresenter createPresenter() {
        return new SettingsPresenter();
    }

    @Override
    protected void initView() {
        OnClickListener onClickListener = new OnClickListener();
//        語言
        tvLanguage = fd(R.id.tv_language);
        tvLanguage.setOnClickListener(onClickListener);
//        場地
        tvSite = fd(R.id.tv_site);
        tvSite.setOnClickListener(onClickListener);
//        院友信息導航類被
        tvType = fd(R.id.tv_type);
        tvType.setOnClickListener(onClickListener);
//        圖片
        tvPhoto = fd(R.id.tv_photo);
        tvPhoto.setOnClickListener(onClickListener);
//        角度
        tvAngle = fd(R.id.tv_angle);
        tvAngle.setOnClickListener(onClickListener);
//        当前用户
        tvUser = fd(R.id.tv_user);
        tvUser.setOnClickListener(onClickListener);
//        版本
        tvVersion = fd(R.id.tv_version);
        tvVersion.setText(AppUtil.getInstance().getVersion());
        fd(R.id.ll_version).setOnClickListener(onClickListener);
        fd(R.id.btn_log_out).setOnClickListener(onClickListener);
    }

    @Override
    protected void initData() {
        tvLanguage.setText(LanguageUtils.getInstance().getStrLanguage());
        tvSite.setText(SPUtil.getInstance().getString(AllConstants.SITE_NAME));
        int oldType = SPUtil.getInstance().getInt(AllConstants.INFO_TYPE, 1);
        tvType.setText(oldType == 1 ? R.string.floor : R.string.member_type);
        tvAngle.setText(getString(R.string.angle_show, SPUtil.getInstance().getInt(AllConstants.FACE_ANGLE, 0)));
        int photoType = SPUtil.getInstance().getInt(AllConstants.PHOTO_TYPE, 1);
        tvPhoto.setText(photoType == 1 ? R.string.photo_register : R.string.photo_identify);
        tvUser.setText(SPUtil.getInstance().getString(AllConstants.USER));
    }

    @Override
    public void onGetSiteSuccess(ApiResultData<List<ShortDto>> apiResultData) {
        if (apiResultData.getStatus() != 2000) {
            ToastUtil.showToast(apiResultData.getMessage());
            return;
        }
        new ShortDialog(context, apiResultData.getData(), R.string.site,
                SPUtil.getInstance().getString(AllConstants.SITE_ID),
                bean -> mPresenter.changeSite(bean.getName(), bean.getId())).show();
    }

    @Override
    public void onGetSiteFail(Exception e) {
        ToastUtil.showToast(R.string.network_error);
    }

    @Override
    public void onUploadSiteSuccess(ApiResultData<String> apiResultData, String siteName, String siteId) {
        if (apiResultData.getStatus() != 2000) {
            ToastUtil.showToast(apiResultData.getMessage());
            return;
        }
        SPUtil.getInstance().putString(AllConstants.SITE_ID, siteId);
        SPUtil.getInstance().putString(AllConstants.SITE_NAME, siteName);
        NotificationUtil.getInstance().getNotificationManager().cancelAll();
        context.stopService(new Intent(context, CloseService.class));
        EventBus.getDefault().post(new Event(EventCode.EVENT_SITE));
    }

    @Override
    public void onUploadSiteFail(Exception e) {
        ToastUtil.showToast(R.string.network_error);
    }

    @Override
    public void onUploadLanguageSuccess(ApiResultData<String> apiResultData) {
    }

    @Override
    public void onUploadLanguageFail(Exception e) {
    }

    @Override
    public void onGetVersionSuccess(final ApiResultData<VersionDto> apiResultData) {
        if (apiResultData.getStatus() == 2000) {
            if (apiResultData.getData() != null) {
                int newVersion;
                int myVersion;
                try {
                    newVersion = Integer.parseInt(apiResultData.getData().getVersion().replace(".", ""));
                    myVersion = Integer.parseInt(AppUtil.getInstance().getVersion().replace(".", ""));
                } catch (NumberFormatException e) {
                    ToastUtil.showToast(R.string.version_error);
                    e.printStackTrace();
                    return;
                }
                if (newVersion > myVersion) {
                    CommDialogUtils.showDialog(context, getString(R.string.new_version),
                            apiResultData.getData().getDesc(), R.string.download,
                            new CommDialogUtils.DialogClickListener() {
                                @Override
                                public void cancelClick() {

                                }

                                @Override
                                public void okClick() {
                                    String fileName = apiResultData.getData().getOutputFile();
                                    File file = new File(getActivity().getCacheDir(), fileName);
                                    if (file.exists()) file.delete();// 已下載過安裝包
                                    else file.getParentFile().mkdirs();
                                    // 展示進度條
                                    CommDialogUtils.showProgressDialog(context);
                                    mPresenter.downloadFile(fileName, file);
                                }
                            });
                } else {
                    ToastUtil.showToast(R.string.is_new_version);
                }
            } else {
                ToastUtil.showToast(R.string.version_null);
            }
        }
    }

    @Override
    public void onGetVersionFails(Exception e) {
        ToastUtil.showToast(R.string.network_error);
    }

    @Override
    public void onDownloadFileSuccess(File file) {
        AppUtil.getInstance().installApk(getActivity(), file);
        CommDialogUtils.dismissProDialog();
    }

    @Override
    public void onDownloadProgress(int progress) {
        CommDialogUtils.setProgress(progress);
    }

    @Override
    public void onDownloadFails(Exception e) {
        ToastUtil.showToast(R.string.download_error);
        CommDialogUtils.dismissProDialog();
    }

    @Override
    public void onLogoutSuccess(ApiResultData<String> apiResultData) {
        if (apiResultData.getStatus() != 2000) {
            ToastUtil.showToast(apiResultData.getMessage());
            return;
        }
        NotificationUtil.getInstance().getNotificationManager().cancelAll();
        context.stopService(new Intent(context, CloseService.class));
        ActivityUtil.getInstance().finishActivity();
    }

    @Override
    public void onLogoutFail(Exception e) {
        ToastUtil.showToast(R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(context);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class OnClickListener implements View.OnClickListener {

        @Override
        public void onClick(final View v) {
            int id = v.getId();
            if (id == R.id.tv_language) {
                if (listLang == null) {
                    listLang = new ArrayList<>();
                    listLang.add(new ShortDto("2", getString(R.string.english)));
                    listLang.add(new ShortDto("1", getString(R.string.chinese)));
                    dialogLang = new ShortDialog(context, listLang, R.string.p_sel, SPUtil.getInstance().getInt(AllConstants.LANGUAGE, 1) + "",
                            bean -> {
                                int languageId = Integer.parseInt(bean.getId());
                                SPUtil.getInstance().putInt(AllConstants.LANGUAGE, languageId);
                                mPresenter.changeLanguage(languageId);
                                EventBus.getDefault().post(new Event(EventCode.EVENT_LANGUAGE));
                            });
                }
                dialogLang.show();
            } else if (id == R.id.tv_site) {
                mPresenter.getSite();
            } else if (id == R.id.tv_type) {
                new InfoNavTypeDialog(context, checkedId -> {
                    int newType = checkedId == R.id.rb_floor ? 1 : 2;
                    SPUtil.getInstance().putInt(AllConstants.INFO_TYPE, newType);
                    tvType.setText(newType == 1 ? R.string.floor : R.string.member_type);
                    EventBus.getDefault().post(new Event(EventCode.EVENT_MEMBER_TYPE));
                }).show();
            } else if (id == R.id.tv_photo) {
                if (listPhoto == null) {
                    listPhoto = new ArrayList<>();
                    listPhoto.add(new ShortDto("1", getString(R.string.photo_register)));
                    listPhoto.add(new ShortDto("2", getString(R.string.photo_identify)));
                    dialogPhoto = new ShortDialog(context, listPhoto, R.string.p_sel, SPUtil.getInstance().getInt(AllConstants.PHOTO_TYPE, 1) + "",
                            bean -> {
                                int newType = Integer.parseInt(bean.getId());
                                SPUtil.getInstance().putInt(AllConstants.PHOTO_TYPE, newType);
                                tvPhoto.setText(newType == 1 ? R.string.photo_register : R.string.photo_identify);
                                EventBus.getDefault().post(new Event(EventCode.EVENT_PHOTO_TYPE));
                            });
                }
                dialogPhoto.show();
            } else if (id == R.id.ll_version) {
                mPresenter.getVersion();
            } else if (id == R.id.tv_angle) {
                startActivityForResult(new Intent(context, CameraAngleActivity.class), 1);
            } else if (id == R.id.tv_user) {
                Intent intent = new Intent(context, LoginActivity.class);
                intent.putExtra(AllConstants.WHAT, 1);
                startActivity(intent);
            } else if (id == R.id.btn_log_out) {
                mPresenter.logOut();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            tvAngle.setText(getString(R.string.angle_show, SPUtil.getInstance().getInt(AllConstants.FACE_ANGLE, 0)));
        }
    }
}
